package main

import "fmt"

var array [][]int = [][]int{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}

func main() {
	i := spiralArray(array)
	fmt.Println(i)
}

// 螺旋遍历数组
func spiralArray(array [][]int) []int {
	//先判断是否为空
	if len(array) == 0 || len(array[0]) == 0 {
		return []int{}
	}
	var n = len(array[0]) //宽度
	var m = len(array)    //高度
	//定义一个切片
	var nums []int = make([]int, n*m)
	var top = 0
	var bottom = m - 1 //高度
	var left = 0
	var right = n - 1 //宽度
	var i = 0
	var j = 0
	var index = 0
	for index < len(nums) {
		for i = left; i <= right; i++ {
			nums[index] = array[top][i]
			index += 1
		}
		top++
		if top > bottom {
			break

		}
		for j = top; j <= bottom; j++ {
			nums[index] = array[j][right]
			index++
		}
		right--
		if left > right {
			break
		}
		for i = right; i >= left; i-- {
			nums[index] = array[bottom][i]
			index++
		}
		bottom--
		if top > bottom {
			break
		}
		for j = bottom; j >= top; j-- {
			nums[index] = array[j][left]
			index++
		}
		left++
		if left > right {
			break
		}
	}
	return nums
}
